package com.defysoft.waukids.slide;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.Custom_Data_Type.Bc_Student_Che;
import com.defysoft.waukids.JsonParser;
import com.defysoft.waukids.R;

public class Slide_MemberStudent_Connect_A extends BaseActivity implements OnClickListener{
	String PK_Stu_Code, PK_Mem_Email;
	TextView tv[] = new TextView[2];
	EditText et;
	Bc_Student_Che bc_Student_Che;
	boolean checkStudent = false;			//자녀코드확인 버튼 눌렀는지 확인.
	private final int SEARCH_CODE = 10;		//자녀코드 자녀매칭 확인
	private final int INSERT_CODE = 9;		//자녀코드 입력
	private final int SEARCH_SUCCESS = 8;		//코드검색 성공
	private final int SEARCH_FAILURE = 7;		//코드검색 실패
	private final int INSERT_SUCCESS = 6;		//자녀코드 입력
	private final int INSERT_FAILURE = 5;		//자녀코드 입력
	
	Toolbar toolbar;
	Spinner spinner;
	String[] celebrities = {"확인","등록"};

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		PK_Mem_Email = getIntent().getStringExtra("PK_Mem_Email");
		setContentView(R.layout.slide_memberstudent_connect_a);
		setStartData();
		setStartToolbar();
	}
	
	@Override
	public void setStartData() {
		super.setStartData();
		PK_Stu_Code = getIntent().getStringExtra("PK_Stu_Code");
		tv[0] = (TextView)findViewById(R.id.SLIDE_MEMBERSTUDENT_CONNECT_MATCHCHECK);	//자녀코드 확인
		tv[1] = (TextView)findViewById(R.id.SLIDE_MEMBERSTUDENT_CONNECT_BTN);			//자녀등록 버튼
		tv[0].setOnClickListener(this);
		tv[1].setOnClickListener(this);
		et = (EditText)findViewById(R.id.SLIDE_MEMBERSTUDENT_CONNECT_NAME);			//자녀코드.
		checkStudent = false;
		toolbar = (Toolbar) findViewById(R.id.NSLIDE_MEMBERSTUDENT_CONNECT_TOOL);
		spinner = (Spinner) findViewById(R.id.SLIDE_MEMBERSTUDENT_CONNECT_SPI);
		
		//코드확인 뒤 수정하면 다시 확인.
		et.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				checkStudent  = false;
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			@Override
			public void afterTextChanged(Editable s) {
				
			}
		});
	}
	
	private void setStartToolbar() {
		spinner.setAdapter(
				new ArrayAdapter<String>(this, 0){
			@Override
			public int getCount() {
				return celebrities.length;
			}
			@Override
			public View getDropDownView(int position, View convertView,
					ViewGroup parent) {
				final int pos = position;
				if (convertView == null) {
					convertView = getLayoutInflater().inflate(
							R.layout.overflowitem_row, null);
				}
            ((TextView) convertView.findViewById(R.id.OVERFLOWITEM_TV))
						.setText(celebrities[position]);
				convertView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						switch (pos) {
						case 0:
							if (et.getText().length() == 0) {
								Toast.makeText(Slide_MemberStudent_Connect_A.this, "자녀코드를 입력하세요.", Toast.LENGTH_LONG).show();
							} else{
								startNetwork(SEARCH_CODE);
							}
							
							break;
						case 1:
							if (et.getText().length() == 0) {
								Toast.makeText(Slide_MemberStudent_Connect_A.this, "자녀코드를 입력하세요.", Toast.LENGTH_LONG).show();

							} else{
								if (checkStudent != true) {
									Toast.makeText(Slide_MemberStudent_Connect_A.this, "자녀코드확인을 눌러서 확인해주세요.", Toast.LENGTH_LONG).show();
								}else {
									startNetwork(INSERT_CODE);
								}
							}
							break;
							
							}
							
							
						}
					
				});
				return convertView;
			}

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				final int pos = position;
				if (convertView == null) {
					convertView = getLayoutInflater().inflate(
							R.layout.overflowitem_row, null);
				}
				((TextView) convertView.findViewById(R.id.OVERFLOWITEM_TV))
						.setBackgroundColor(0x00ffffff);
				return convertView;
			}
		});
		
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		/*spinner.setVisibility(View.VISIBLE);*/
	}
	
	
	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);
		switch (_message.what){
		case CATCH_EXCEPTION: // thread 에러 메세지
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}
			checkStudent = false;
			Toast.makeText(this, "자녀코드를 확인해 주세요.", Toast.LENGTH_SHORT).show();
			break;
		case SEARCH_SUCCESS:		//자녀검색 성공.
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}			
			dialog_Delete(1);
			break;
		case SEARCH_FAILURE:			//자녀검색 실패.
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}
			Toast.makeText(this, "자녀코드를 확인해주세요.", Toast.LENGTH_SHORT).show();
			break;
		case INSERT_SUCCESS:			//자녀등록 성공.
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}
			checkStudent = false;
			Toast.makeText(this,"자녀등록 성공", Toast.LENGTH_SHORT).show();
			setResult(SLIDE_MEMBERSTUDENT_CONNECT);
			finish();
			break;
		case INSERT_FAILURE:			//자녀등록 실패.
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}
			checkStudent = false;
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT).show();
			break;
		}
	}
////////////////
	void dialog_Delete(final int pos1) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(bc_Student_Che.Stu_Name+"\n"+bc_Student_Che.schoolname+"\n"+bc_Student_Che.schoolclass+"\n생년월일:"+bc_Student_Che.Stu_Birth).setCancelable(false)
              .setPositiveButton("네", new DialogInterface.OnClickListener() {
                 @Override
                 public void onClick(DialogInterface dialog, int which) {
                	 checkStudent = true;
                     dialog.cancel();
                 }
              })
              .setNegativeButton("아니오", new DialogInterface.OnClickListener() {
                 @Override
                 public void onClick(DialogInterface dialog, int which) {
                	 et.setText("");
                    dialog.cancel();
                 }
              });
        AlertDialog alert = builder.create();
        alert.show();
     }   
////////////////
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.SLIDE_MEMBERSTUDENT_CONNECT_MATCHCHECK:
			if (et.getText().length() == 0) {
				Toast.makeText(this, "자녀코드를 입력하세요.", Toast.LENGTH_LONG).show();
			} else{
				startNetwork(SEARCH_CODE);
			}
			break;
		case R.id.SLIDE_MEMBERSTUDENT_CONNECT_BTN:
			if (et.getText().length() == 0) {
				Toast.makeText(this, "자녀코드를 입력하세요.", Toast.LENGTH_LONG).show();
			} else{
				if (checkStudent != true) {
					Toast.makeText(this, "자녀코드확인을 눌러서 확인해주세요.", Toast.LENGTH_LONG).show();
				}else {
					startNetwork(INSERT_CODE);
				}
			}
			break;
		}
	}

	@Override
	public void startThread(int choice) {
		super.startThread(choice);
		final int cho = choice;
		if(firstThread != null){firstThread.interrupt();}
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				switch (cho) {
				case SEARCH_CODE:		//자녀코드 확인.
					checkCode();
					break;
				case INSERT_CODE:		//자녀코드 입력.
					insertCode();
					break;
				}
			}
		});
		firstThread.start();
		startDIal();
	}
void checkCode(){	//자녀코드 확인.
	JSONObject jsonObject = null;
	try {
			jsonObject = new JSONObject(publicHttpCallback(HTTP_MEMBERSTUDENT_MATCHCHECK, "PK_Mem_Email="+PK_Mem_Email+"&PK_Stu_Code="+et.getText().toString()));
			if (jsonObject.getBoolean("success")) {
				bc_Student_Che = JsonParser.StudentDetail(jsonObject.getString("payload"));
				onNetworkCallback(SEARCH_SUCCESS, "");
			} else {
				onNetworkCallback(SEARCH_FAILURE, jsonObject.getString("message"));
			}
	} catch (Exception e) {
		onNetworkCallback(CATCH_EXCEPTION, e.toString());
	}	
}
void insertCode(){	//자녀코드 입력.
	JSONObject jsonObject = null;
	try {
			jsonObject = new JSONObject(publicHttpCallback(HTTP_MEMBERSTUDENT_CONNECT, "PK_Mem_Email="+PK_Mem_Email+"&PK_Stu_Code="+et.getText().toString()));
			if (jsonObject.getBoolean("success")) {
				bc_Student_Che = JsonParser.StudentDetail(jsonObject.getString("payload"));
				onNetworkCallback(INSERT_SUCCESS, "");
			} else {
				onNetworkCallback(INSERT_FAILURE, jsonObject.getString("message"));
			}
	} catch (Exception e) {
		onNetworkCallback(CATCH_EXCEPTION, e.toString());
	}	
}
}//CLASS_END
